<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/**
 * 商品表控制器
 * 通过 id 获取 单条数据
 * @author 周英勇 15913362842@163.com
 */
class Goods extends Web_Controller {
     
    public function __construct()
    {
        parent::__construct();
        $this->load->model('Goods_model','goods_model');
        $this->load->model('Activity_model','activity_model');
        $this->load->model('Zone_model','zone_model');
        $this->load->library('upload');
        $this->load->library('PHPExcel');
        $this->load->helper('Excel');
        $this->userSession();
    }
	
	/**
	*商品banner图列表
	*输出上架商品的banner活动图
	*根据创建时间排序
	*/
	public function index()
	{   
        $data['base_path'] = $this->config->item('base_url').'static/upload/goods/';
		$activity_id = $this->input->get('activity_id');
        $goods_name = $this->input->get('goods_name');
        $data['info'] = $this->goods_model->getGoodsList($activity_id,$goods_name);
        if(!empty($data['info'])){
            foreach($data['info'] as $key => $value){
                $res = $this->JsonsToArray($value['banner_img']);
                $data['info'][$key]['img_path'] = isset($res['img_path'][0])?$res['img_path'][0]:'';
                $data['info'][$key]['img_name'] = isset($res['img_name'][0])?$res['img_name'][0]:'';
            }
        }
        $data['base_url'] = $this->config->item('base_url');
        $data['activity'] = $this->activity_model->getActivitysByStatus();

		$this->load->view('admin/header');
		$this->load->view('admin/goodslist',$data);
        $this->load->view('admin/tail');
	}
 

	/**
    *添加商品页面
    */
    public function createHtml(){
        $goods_id = $this->input->get('goods_id');
        $data['base_path'] = $this->config->item('base_url').'static/upload/goods/';
        if(isset($goods_id)){
            $data['info'] = $this->goods_model->getGoodsById($goods_id);
            $data['info']['banner_img'] = $this->JsonsToArray($data['info']['banner_img']);
            $data['info']['ads_img'] = $this->JsonsToArray($data['info']['ads_img']);
            $data['info']['status'] = $data['info']['status'] == '2' ? 'on' : 'off';
        }else{
            $data['info'] = array('name'=>'','other_name'=>'','price'=>'','descript'=>'','banner_img'=>'','ads_img'=>'','status'=>'on','goods_detail'=>'','goods_params'=>'','goods_id'=>'','activity_id'=>'');
        }
        $data['info']['activity'] = $this->activity_model->getActivitysByStatus();
        $this->load->view('admin/header');
        $this->load->view('admin/goodsinfo',$data);
    }
    
    /*
    *把一条地址图片名称关联的json数组转换成数组
    *params $json
    *data $array['img_path']:图片路径,$array['img_name']:图片名;
    */
    public function JsonSToArray($json){
        $res = json_decode($json,true);
        $data = array();
        if(!empty($res)){
            foreach($res as $key => $value){                
                $data['img_path'][] = $key;
                $data['img_name'][] = $value;
            }
        }

        return $data;
    }
   /**
    *添加或修改一条商品
    */
    public function editGoods(){
        $data = $this->input->post();

        $count = count($_FILES['img']['name']);
        if($count > 4){
            echo "操作失败，轮播图最多只能插入三张<a onclick='history.back(-1)' style='color:blue'>，点击返回</a>";
            exit();
        }
       
        for($i=0;$i<$count;$i++){
            $_FILES['img'.$i]=array(
                'name'=>$_FILES['img']['name'][$i],
                'type'=>$_FILES['img']['type'][$i],
                'tmp_name'=>$_FILES['img']['tmp_name'][$i],
                'error'=>$_FILES['img']['error'][$i],
                'size'=>$_FILES['img']['size'][$i]
            );
            $config = array();
            $config['upload_path'] = FCPATH . 'static/upload/goods/' . date('Ym');
            @mkdir($config['upload_path']);
            $config['allowed_types'] = 'jpg|png|git';
            $config['encrypt_name'] = true;
            $this->upload->initialize($config);
            $img_state = $this->upload->do_upload('img'.$i);
            $img[$i] = $this->upload->data();
            if($i == 0){
                $banner_url[date('Ym').'/'.$img[$i]['file_name']] = $img[$i]['client_name'];
            }else{
                $ads_url[date('Ym').'/'.$img[$i]['file_name']] = $img[$i]['client_name'];
            }
            if ($_FILES['img'.$i]['size'] > 0 && $img_state == false) {// 有上传文件但上传失败
                echo "图片上传失败<a onclick='history.back(-1)' style='color:blue'>，点击返回</a>";
                exit();
            }
        }
        if(!empty($_FILES['img']['name'][0])){ 
            $data['banner_img'] = json_encode($banner_url);
        }
        if(!empty($_FILES['img']['name'][1])){
            $data['ads_img'] = json_encode($ads_url);
        }

        $data['status'] = isset($data['status']) ? '2' : '1';

        $data['update_time'] = strtotime(date("Y-m-d H:i:s"));
        if(!empty($data['goods_id'])){//编辑页面
            $query = $this->checkdata($data);

            if($query == 0){ 
                $id = $this->goods_model->updateGoodsById($data['goods_id'],$data);
            }
        }else{
            if($_FILES['img']['name'][0]=='')
            {
                echo "操作失败，banner图不能为空<a onclick='history.back(-1)' style='color:blue'>，点击返回</a>";
                exit();
            }
            if($_FILES['img']['name'][1]=='')
            {
                echo "操作失败，轮播图不能为空<a onclick='history.back(-1)' style='color:blue'>，点击返回</a>";
                exit();
            }
            $data['create_time'] = strtotime(date("Y-m-d H:i:s"));
            unset($data['goods_id']);
            $query = $this->checkdata($data);
            if($query == 0){ 
                $id = $this->goods_model->addGoods($data);
            }
        }
        if($id){
            header("location:{$this->base_url}admin/goods/index");
        }else{
            echo "操作失败，<a onclick='history.back(-1)' style='color:blue'>点击返回</a>";
        }
    }
	/**
	*删除一条商品
	*/
	public function delete(){

	}
    public function checkdata($data){
        foreach($data as $key => $value){
                if($key == 'descript'){
                     continue;
                }
                if($value == ""){
                    echo "插入输入不完整，<a onclick='history.back(-1)' style='color:blue'>点击返回</a>";
                    exit;
                }
        }
        return 0;
    }
	public function outputExcel(){
		$res = $info = $this->goods_model->getGoodsImgByStatus();
		var_dump($res);die();
	}
    

    public function download(){
    	$header = array("主键","库存","商品名","价格","状态","创建时间");
    	$res = $this->goods_model->getGoods();
    	excel_download($header,$res);
    }
    public function uploadHtml(){
    	$data['base_url'] = $this->config->item('base_url');
    	$this->load->view('home/excel_upload');
    }
    public function  upload(){
    	
    	  
    	$url = 'application\upload\goods\\'. date('Ym').'\\'.$excel['file_name'];
    	$data = excel_upload($url);
        var_dump($data);

    }

  
}
